package com.example.wechatappbackend.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.wechatappbackend.common.CommonResponse;
import com.example.wechatappbackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.rmi.CORBA.Util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/accounts/")
public class AccountController {

    @Autowired
    private UserService userService;

    @GetMapping("openId")
    public JSONObject getUserOpenId(@RequestParam("code")String code) throws Exception {
        System.out.println("code:"+code);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxe61d22a7a009463c&secret=77d624f183ada712ca790ada2e82c4bc&js_code="+code+"&grant_type=authorization_code";
        URLConnection urlConnection = new URL(url).openConnection();
        HttpURLConnection connection = (HttpURLConnection) urlConnection;
        connection.setRequestMethod("GET");
        connection.connect();

        int responseCode = connection.getResponseCode();
        JSONObject jsonObject = null;
        if (responseCode == HttpURLConnection.HTTP_OK) {
//            JSONObject jsonObject = new JSONObject(new  InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader
                    (connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder bs = new StringBuilder();
            String l;
            while ((l = bufferedReader.readLine()) != null) {
                bs.append(l).append("\n");
            }
            String content = null;
            content = bs.toString();
            System.out.println("content:"+content);
            jsonObject =  JSON.parseObject(content);
        }
        return jsonObject;
    }

    @RequestMapping("add")
    public void addNewAccount(@RequestParam("openId")String openId, @RequestParam("nickName")String nickName, @RequestParam("avatar")String avatar){

        System.out.println(openId+" "+nickName+" "+avatar);
        userService.addNewUser(openId,nickName,avatar);
    }


}
